﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    [HotUpdate]
    [Description("保证金收款单保存后反写销售订单关联补充保证金")]
    public class ReceiveBillSave : AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string billType = entity["BillTypeID_Id"].ToString();
                if (billType == "58c77e15e6566a")
                {
                    string orderBillno = string.Empty;
                    DynamicObjectCollection srcEntries = (DynamicObjectCollection)entity["RECEIVEBILLSRCENTRY"];
                    Dictionary<string, decimal> billRealRecAmounts = new Dictionary<string, decimal>();

                    //更新明细行并按单号统计收款金额
                    foreach(DynamicObject srcEntry in srcEntries)
                    {
                        orderBillno = srcEntry["ORDERBILLNO"].ToString();
                        int srcMaterialSeq = Convert.ToInt16(srcEntry["FSRCMATERIALSEQ"]);
                        decimal realRecAmount = Convert.ToDecimal(srcEntry["FREALRECAMOUNTFOR"]);
                        if(!billRealRecAmounts.ContainsKey(orderBillno))
                        {
                            billRealRecAmounts.Add(orderBillno, realRecAmount);
                        }
                        else
                        {
                            billRealRecAmounts[orderBillno] += realRecAmount;

                        }
                        string sqlEntry = string.Format(@"/*dialect*/
                                UPDATE T_SAL_ORDERENTRY SET F_PMAF_RECIEVEDEARNEST={0}
                                WHERE FID=(SELECT FID FROM T_SAL_ORDER WHERE FBILLNO='{1}')
                                AND FSEQ={2}
                                ", realRecAmount, orderBillno, srcMaterialSeq);
                        DBUtils.Execute(Context, sqlEntry);
                    }
                    //按单更新表头收款金额
                    foreach(KeyValuePair<string, decimal> billRealRecAmount in billRealRecAmounts)
                    {
                        string billno = billRealRecAmount.Key;
                        decimal realRecAmount = billRealRecAmount.Value;
                        string sql = string.Format(@"/*dialect*/
                                    UPDATE T_SAL_ORDER SET F_PMAF_ASSOCIATEEARNEST={0}
                                    WHERE FBILLNO='{1}'", realRecAmount, billno);
                        DBUtils.Execute(Context, sql);
                    }

                }
            }
        }
    }
}
